package com.xiaoyu.base.view.list.util.diff;

import java.util.ArrayList;
import java.util.List;

import in.srain.cube.util.CheckUtil;
import in.srain.cube.views.list.CubeRecyclerViewSimpleAdapter;
import in.srain.cube.views.list.ListItemTypedBase;

public abstract class BaseDiffAdapter<T extends ListItemTypedBase> extends CubeRecyclerViewSimpleAdapter<T> implements DiffAdapter<T> {

    private final BackgroundDiffExecutor<T> mBackgroundDiffExecutor = new BackgroundDiffExecutor<>(this);

    public BaseDiffAdapter() {
        mList = new ArrayList<>(); // final
    }

    @Override
    @Deprecated
    public void setList(List<T> list) {
        replaceList(list);
    }

    private void replaceList(List<T> list) {
        mList.clear();
        mList.addAll(list);
    }

    public void update(List<T> newList) {
        update(newList, null);
    }

    public void update(List<T> newList, OnUpdateCompleteListener updateListListener) {
        mBackgroundDiffExecutor.enqueue(DiffPayload.obtain(newList, updateListListener));
    }

    public void applyResult(DiffPayload payload) {
        CheckUtil.checkMain();

        replaceList((List<T>) payload.getNewList());
        payload.getDiffResult().dispatchUpdatesTo(this);

        if (payload.getOnUpdateFinishListener() != null) {
            payload.getOnUpdateFinishListener().onUpdateComplete();
        }

        DiffPayload.release(payload);
    }

    public interface OnUpdateCompleteListener {

        void onUpdateComplete();
    }
}
